import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author Jiabin
 * 
 */
public class Utility
{
    public static byte[] serializeObj(Object obj)
    {
        try
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeObject(obj);
            out.close();
            return bos.toByteArray();
        }
        catch (IOException e)
        {
            System.err.println("Error when serializing object.");
            e.printStackTrace();
            return null;
        }
    }

    public static Object deserializeObj(byte[] bytes)
    {
        try
        {
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Object obj = in.readObject();
            in.close();
            return obj;
        }
        catch (Exception e)
        {
            System.err.println("Error when deserializing object.");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param addrStr
     *            must be valid IPv4 address string, in the form of "x.x.x.x".
     * @return
     */
    public static InetAddress buildInetAddr(String addrStr)
    {
        String[] segaments = addrStr.split("\\.");
        byte[] rawAddr = new byte[4];
        for (int i = 0; i < 4; ++i)
            rawAddr[i] = (byte) Integer.parseInt(segaments[i]);

        try
        {
            return InetAddress.getByAddress(rawAddr);
        }
        catch (UnknownHostException e)
        {
            System.err.format("Error when interpreting IP address %s\n", addrStr);
            e.printStackTrace();
            return null;
        }
    }

    public static String buildIPString(InetAddress addr)
    {
        byte[] rawAddr = addr.getAddress();
        String ipString = "";
        int i = 4;
        for (byte b : rawAddr)
        {
            ipString += (b & 0xFF);
            if (--i > 0)
                ipString += '.';
        }
        return ipString;
    }

    public static void debugInfo(String s)
    {
        // System.out.println(s);
    }
}
